import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { LoginForm, RegisterForm } from './types';
import { authService } from './api';
import { authStore } from './store';

/**
 * 使用认证相关的逻辑
 */
export function useAuth() {
  const router = useRouter();
  // 响应式数据
  const currentTab = ref<'login' | 'register'>('login');
  const isLoading = ref(false);
  const showPassword = ref(false);
  const showRegPassword = ref(false);
  const showConfirmPassword = ref(false);

  // 表单数据
  const loginForm = reactive<LoginForm>({
    phoneNumber: '',
    password: '',
    remember: false
  });

  const registerForm = reactive<RegisterForm>({
    fullName: '',
    phoneNumber: '',
    email: '',
    password: '',
    confirmPassword: '',
    organization: '',
    agreeTerms: false
  });

  // 错误信息
  const errors = reactive<Record<string, string>>({});

  // 切换标签页
  const switchTab = (tab: 'login' | 'register') => {
    currentTab.value = tab;
  };

  // 清除错误信息
  const clearError = (field: string) => {
    if (errors[field]) {
      delete errors[field];
    }
  };

  // 表单验证
  const validateField = (field: string) => {
    switch (field) {
      case 'phoneNumber':
        if (!loginForm.phoneNumber.trim()) {
          errors.phoneNumber = '请输入手机号码';
        } else if (!/^1\d{10}$/.test(loginForm.phoneNumber)) {
          errors.phoneNumber = '请输入有效的手机号码';
        } else {
          delete errors.phoneNumber;
        }
        break;
      case 'password':
        if (!loginForm.password) {
          errors.password = '请输入密码';
        } else if (loginForm.password.length < 6) {
          errors.password = '密码长度不能少于6位';
        } else {
          delete errors.password;
        }
        break;
      case 'fullName':
        if (!registerForm.fullName.trim()) {
          errors.fullName = '请输入真实姓名';
        } else {
          delete errors.fullName;
        }
        break;
      case 'regPhoneNumber':
        if (!registerForm.phoneNumber.trim()) {
          errors.regPhoneNumber = '请输入手机号码';
        } else if (!/^1\d{10}$/.test(registerForm.phoneNumber)) {
          errors.regPhoneNumber = '请输入有效的手机号码';
        } else {
          delete errors.regPhoneNumber;
        }
        break;
      case 'email':
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!registerForm.email.trim()) {
          errors.email = '请输入邮箱地址';
        } else if (!emailRegex.test(registerForm.email)) {
          errors.email = '请输入有效的邮箱地址';
        } else {
          delete errors.email;
        }
        break;
      case 'regPassword':
        if (!registerForm.password) {
          errors.regPassword = '请输入密码';
        } else if (registerForm.password.length < 8) {
          errors.regPassword = '密码长度不能少于8位';
        } else if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(registerForm.password)) {
          errors.regPassword = '密码必须包含大小写字母和数字';
        } else {
          delete errors.regPassword;
        }
        break;
      case 'confirmPassword':
        if (!registerForm.confirmPassword) {
          errors.confirmPassword = '请确认密码';
        } else if (registerForm.confirmPassword !== registerForm.password) {
          errors.confirmPassword = '两次输入的密码不一致';
        } else {
          delete errors.confirmPassword;
        }
        break;
      case 'organization':
        if (!registerForm.organization.trim()) {
          errors.organization = '请输入所在机构名称';
        } else {
          delete errors.organization;
        }
        break;
    }
  };

  // 登录处理
  const handleLogin = async (e: Event) => {
    e.preventDefault();
    
    // 验证所有字段
    validateField('phoneNumber');
    validateField('password');
    
    // 检查是否有错误
    if (errors.phoneNumber || errors.password) {
      return;
    }
    
    isLoading.value = true;
    
    try {
      // 登录并获取token
      const { token } = await authService.login({
        phoneNumber: loginForm.phoneNumber,
        password: loginForm.password
      });
      
      // 登录成功处理
      console.log('登录成功');
      
      // 设置认证状态
      authStore.setAuth(token, loginForm.phoneNumber);
      
      // 设置登录状态和用户名
      localStorage.setItem('isLoggedIn', 'true');
      localStorage.setItem('username', loginForm.phoneNumber);
      
      // 跳转到首页
      router.push('/home');
    } catch (error) {
      console.error('登录失败:', error);
      // 设置登录错误信息
      errors.loginError = error instanceof Error ? error.message : '登录失败，请检查账号密码';
    } finally {
      isLoading.value = false;
    }
  };

  // 登出处理
  const handleLogout = async () => {
    try {
      // 调用登出API
      await authService.logout();
      
      // 清除认证状态（包括token、userId、isLoggedIn和username）
      authStore.clearAuth();
      
      // 重定向到登录页面
      router.push('/');
    } catch (error) {
      console.error('登出失败:', error);
      alert('登出失败，请稍后重试');
    }
  };

  return {
    currentTab,
    isLoading,
    showPassword,
    showRegPassword,
    showConfirmPassword,
    loginForm,
    registerForm,
    errors,
    switchTab,
    clearError,
    validateField,
    handleLogin,
    handleLogout
  };
}